package com.xcm.util;

import org.apache.commons.lang3.StringUtils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.*;

/**
 * 检查帮助类
 *
 * @author 林强
 * @date 2018-04-12 11:15
 */
public class CheckUtil {

    private static final String UNDEFINED = "undefined";

    /**
     * 获取对象某个字段的值
     *
     * @param obj   对象
     * @param field 字段名
     * @return
     */
    public static Object getFieldValue(Object obj, String field) {
        Object o = null;
        if (obj == null) {
            return null;
        }
        try {
            Class<? extends Object> clazz = obj.getClass();
            PropertyDescriptor pd = new PropertyDescriptor(field, clazz);
            if (pd == null) {
                return null;
            }
            Method getMethod = pd.getReadMethod();// 获得get方法
            if (getMethod == null) {
                return null;
            }
            o = getMethod.invoke(obj);// 执行get方法返回一个Object
            if (o == null) {
                return null;
            }
            if ("".equals(o)) {
                return null;
            }
        } catch (SecurityException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return null;
        } catch (IntrospectionException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return null;
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            return null;
        }
        return o;
    }

    /**
     * 若字符串长度大于1，字符串以指定符号隔开，若最后一位为指定符号，则去除，若不是，则返回原字符串
     * 若字符串长度为1，并且为指定符号，则返回空字符，否则返回原字符串
     *
     * @param separateStr
     * @param targetStr
     * @return
     */
    public static String removeLastChar(String separateStr, String targetStr) {
        if (StringUtils.isBlank(targetStr)) {
            return targetStr;
        }
        if (StringUtils.isBlank(separateStr)) {
            return targetStr;
        }
        if (targetStr.length() > 1) {
            if (StringUtils.endsWith(targetStr, separateStr)) {
                targetStr = StringUtils.removeEnd(targetStr, separateStr);
            }
            return targetStr;
        }
        return targetStr.equals(separateStr) ? "" : targetStr;
    }

    public static void main(String[] args) {
        System.out.println(removeLastChar(",", ","));
    }
}
